package com.glorysoft.xztpda.ui.fttrackin

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.glorysoft.xztpda.entity.ui.ToastMessageBean
import com.glorysoft.xztpda.BR
import com.glorysoft.xztpda.R
import com.glorysoft.xztpda.base.BaseActivity
import com.glorysoft.xztpda.databinding.ActivityFtTrackInBinding
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import kotlinx.android.synthetic.main.activity_ft_track_in.*
import kotlinx.android.synthetic.main.activity_ft_track_in.etCarrier
import kotlinx.android.synthetic.main.activity_ft_track_in.etItemEqp
import kotlinx.android.synthetic.main.activity_ft_track_in.etLotID
import kotlinx.android.synthetic.main.activity_ft_track_in.ivLotScan
import kotlinx.android.synthetic.main.activity_ft_track_in.rvCarrierList
import kotlinx.android.synthetic.main.activity_track_in_guide.*
import java.io.Serializable

/**
 * FileName: FTTackinActivity
 * Author: XJH
 * Date: 2022/4/12 18:09
 * Description:
 * History:
 */
class FTTrackInActivity : BaseActivity<FTTrackInBaseViewModel, ActivityFtTrackInBinding>(),
        View.OnClickListener {
    override fun layoutId(): Int {
        return R.layout.activity_ft_track_in
    }

    override fun initVariableId(): Int {
        return BR.fTTrackInBaseViewModel
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle("FT进站")
        addActivity(this)
        setRightListener("下一步") {
            if (viewModel.lotInfoEntity == null) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请先获取批次信息", false)
                return@setRightListener
            }

            if (etMainEqp.text.toString().isEmpty()) {
                viewModel.defUI.toastEvent.value = ToastMessageBean("请输入分选机ID", false)
                return@setRightListener
            }

            val checkList = viewModel.mCarrierAdapter.checkList
            for (i in 0 until checkList.size()) {
                if (!checkList[i]) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前有载具未校验", false)
                    return@setRightListener
                }
            }

            if (viewModel.materialItems.isNotEmpty()) {
                viewModel.materialItems.forEach{
                    if (it.mlotid.isEmpty()){
                        viewModel.defUI.toastEvent.value = ToastMessageBean("当前有物料批号未填入", false)
                        return@setRightListener
                    }
                }
            }

            viewModel.checkMaterialList(etMainEqp.text.toString(), etLotID.text.toString())

        }

        rvItemEqp.adapter = viewModel.mAddItemEqpAdapter
        rvCarrierList.adapter = viewModel.mCarrierAdapter

        ivLotScan.setOnClickListener(this)
        ivMainScan.setOnClickListener(this)
        ivItemScan.setOnClickListener(this)
        ivCarrierScan.setOnClickListener(this)
    }

    override fun initData() {
        initEdit(etLotID, object : EditTextListener {
            override fun onTextChangeListener(s: String) {
                viewModel.getLotInfo(s)
            }

        })

        initEdit(etItemEqp, object : EditTextListener {
            override fun onTextChangeListener(s: String) {
                if (viewModel.itemEqpList.contains(s)) {
                    viewModel.mAddItemEqpAdapter.data.clear()
                    viewModel.mAddItemEqpAdapter.addData(s)
                } else {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("批次子设备列表不包含此设备", false)
                }

            }

        })

        viewModel.defUI.callObserve.observe(this) {
            when (it.type) {
                0 -> {
                    mBinding.setVariable(BR.fTTrackInBaseViewModel, viewModel)
                    viewModel.mCarrierAdapter.setNewData(viewModel.lotInfoEntity?.durablelist)
                    viewModel.getItemEqp(etLotID.text.toString())
                    scanCarrier()
                }
                1 -> {
                    val bundle = Bundle()
                    viewModel.lotInfoEntity?.lot?.equipmentid = etMainEqp.text.toString()
                    bundle.putSerializable("LOTINFO", viewModel.lotInfoEntity)
                    bundle.putSerializable(
                            "ITEMEQP",
                            viewModel.mAddItemEqpAdapter.data as Serializable
                    )
                    startActivity(FTTrackInNextActivity::class.java, bundle)
                }
                2 -> {
                    etMainEqp.setText("")
                }
                200 ->{
                    startScanForCode(this,1000 + viewModel.scanPos)
                }
                201 ->{
                    getCustomDialog(it.item as String).show()
                }
            }

        }
    }

    /**
     * 载具验证
     */
    private fun scanCarrier() {
        initEdit(etCarrier, object : EditTextListener {
            override fun onTextChangeListener(s: String) {
                etCarrier.setText("")
                Handler().postDelayed({ etCarrier.requestFocus() }, 500)
                if (viewModel.mCarrierAdapter.data.size <= 0) {
                    return
                }

                val data = viewModel.mCarrierAdapter.data
                for (i in data.indices) {
                    if (data[i].equals(s)) {
                        if (viewModel.mCarrierAdapter.checkList?.get(i)!!) {
                            viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具已校验", false)
                        } else {
                            viewModel.mCarrierAdapter.setCheck(s)
                        }
                        return
                    }
                }
                viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具不匹配", false)
            }

        })
    }

    private fun getCustomDialog(code : String): MaterialDialog {
        val dialog = MaterialDialog(this)
                .cancelable(false)
                .cornerRadius(12f)
                .customView(R.layout.check_material, noVerticalPadding = true)
                .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val tv3: TextView = contentView.findViewById(R.id.tv3)
        ivClose.setOnClickListener {
            dialog.dismiss()
        }

        tv3.setOnClickListener {
            viewModel.setMaterial(code)
            dialog.dismiss()
        }

        return dialog
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.ivLotScan -> startScanForCode(this, 10001)
            R.id.ivMainScan -> startScanForCode(this, 10002)
            R.id.ivItemScan -> startScanForCode(this, 10003)
            R.id.ivCarrierScan -> startScanForCode(this, 10004)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        // 当扫码页面结束后，处理扫码结果。
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            return
        }
        if (resultCode == RESULT_OK){
            // 从onActivityResult返回data中，用ScanUtil.RESULT作为key值取到HmsScan返回值。
            when (val obj: Any = data.getParcelableExtra(ScanUtil.RESULT)) {
                is HmsScan -> {
                    val barCode = obj.getOriginalValue()
                    when(requestCode){
                        10001 -> {
                            etLotID.setText(barCode)
                            viewModel.getLotInfo(barCode)
                        }
                        10002 -> {
                            etMainEqp.setText(barCode)
                        }
                        10003 -> {
                            if (viewModel.itemEqpList.contains(barCode)) {
                                viewModel.mAddItemEqpAdapter.data.clear()
                                viewModel.mAddItemEqpAdapter.addData(barCode)
                            } else {
                                viewModel.defUI.toastEvent.value = ToastMessageBean("批次子设备列表不包含此设备", false)
                            }
                        }
                        10004 ->{
                            if (viewModel.mCarrierAdapter.data.size <= 0) {
                                return
                            }

                            val data = viewModel.mCarrierAdapter.data
                            for (i in data.indices) {
                                if (data[i].equals(barCode)) {
                                    if (viewModel.mCarrierAdapter.checkList?.get(i)!!) {
                                        viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具已校验", false)
                                    } else {
                                        viewModel.mCarrierAdapter.setCheck(barCode)
                                    }
                                    return
                                }
                            }
                            viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具不匹配", false)
                        }
                        1000 + viewModel.scanPos ->{
                            viewModel.checkMaterial(barCode)
                        }
                    }
                }
            }


        }
    }
}